package com.zhz.mall.portal.modules.ums.service.impl;

import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhz.mall.common.exception.Asserts;
import com.zhz.mall.portal.modules.ums.mapper.UmsMemberLoginLogMapper;
import com.zhz.mall.portal.modules.ums.mapper.UmsMemberMapper;
import com.zhz.mall.portal.modules.ums.model.UmsMember;
import com.zhz.mall.portal.modules.ums.model.UmsMemberLoginLog;
import com.zhz.mall.portal.modules.ums.service.UmsMemberCacheService;
import com.zhz.mall.portal.modules.ums.service.UmsMemberService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 会员表 服务实现类
 * </p>
 *
 * @author zhouhengzhe
 * @since 2023-02-04
 */
@Service
public class UmsMemberServiceImpl extends ServiceImpl<UmsMemberMapper, UmsMember> implements UmsMemberService {

    @Autowired
    private UmsMemberCacheService memberCacheService;
    @Autowired
    private UmsMemberLoginLogMapper loginLogMapper;
    //@Autowired
    //private PasswordEncoder passwordEncoder;

    /**
     * 获取当前登录用户
     *
     * @return
     */
    @Override
    public UmsMember getCurrentMember() {
        return null;
        //return UserUtil.getMemberDetailsInfo().getUmsMember();
    }

    /**
     * 注册
     *
     * @param umsMemberParam
     * @return
     */
    @Override
    public UmsMember register(UmsMember umsMemberParam) {
        //将密码进行加密操作
        String encodePassword = BCrypt.hashpw(umsMemberParam.getPassword());
        UmsMember umsMember = UmsMember
                .builder()
                .createTime(new Date())
                .status(1)
                .password(encodePassword)
                .build();
        BeanUtils.copyProperties(umsMemberParam, umsMember);
        //查询是否有相同用户名的用户
        QueryWrapper<UmsMember> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(UmsMember::getUsername, umsMember.getUsername());
        List<UmsMember> umsAdminList = list(wrapper);
        if (!CollectionUtils.isEmpty(umsAdminList)) {
            return null;
        }
        baseMapper.insert(umsMember);
        return umsMember;
    }

    /**
     * 登录
     *
     * @param username
     * @param password
     * @return
     */
    @Override
    public UmsMember login(String username, String password) {

        //密码需要客户端加密后传递
        UmsMember umsAdmin = null;
        try {
            //UserDetails userDetails = loadUserByUsername(username);
            //umsAdmin = ((MemberDetails) userDetails).getUmsMember();
            //
            //if (!passwordEncoder.matches(password, umsAdmin.getPassword())) {
            //    Asserts.fail(UserErrorCode.INCORRECT_PASSWORD);
            //}
            //if (!userDetails.isEnabled()) {
            //    Asserts.fail("帐号已被禁用");
            //}
            //insertLoginLog(username);
        } catch (Exception e) {
            Asserts.fail("登录异常:" + e.getMessage());
        }
        return umsAdmin;
    }

    /**
     * 添加登录记录
     *
     * @param username 用户名
     */
    private void insertLoginLog(String username) {
        UmsMember user = getAdminByUsername(username);
        if (Objects.isNull(user)) {
            return;
        }
        UmsMemberLoginLog loginLog = UmsMemberLoginLog
                .builder()
                .memberId(user.getId())
                .createTime(new Date())
                .build();
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (Objects.nonNull(attributes)) {
            HttpServletRequest request = attributes.getRequest();
            loginLog.setIp(request.getRemoteAddr());
        }
        loginLogMapper.insert(loginLog);
    }


    /**
     * 通过用户名获取管理员信息
     *
     * @param username
     * @return
     */
    @Override
    public UmsMember getAdminByUsername(String username) {
        UmsMember user = memberCacheService.getUser(username);
        if (Objects.nonNull(user)) {
            return user;
        }
        QueryWrapper<UmsMember> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(UmsMember::getUsername, username);
        List<UmsMember> adminList = list(wrapper);
        if (!CollectionUtils.isEmpty(adminList)) {
            user = adminList.get(0);
            memberCacheService.setUser(user);
            return user;
        }
        return null;
    }

    /**
     * 通过用户名获取普通用户信息
     *
     * @param username
     * @return
     */
    //@Override
    //public UserDetails loadUserByUsername(String username) {
    //    UmsMember umsMember = getAdminByUsername(username);
    //    if (Objects.nonNull(umsMember)) {
    //        return new MemberDetails(umsMember);
    //    }
    //    throw new ApiException(UserErrorCode.USERNAME_OR_PASSWORD_FAIL);
    //}
}
